//
//  DatePickerViewController.swift
//  EasyDana
//
//  Created by mac on 2024/10/22.
//

import UIKit
import RxSwift
import RxCocoa
class DatePickerViewController: UIViewController {

    
    let confirm = PublishSubject<String>()
    
    private let bag = DisposeBag()
    
    @IBOutlet weak var pickerView: UIPickerView!
    
    private var years: [Int] {
        let date = Date()
        let calendar = Calendar.current
        let comp = calendar.component(.year, from: date)
        return (1970 ... comp).map({$0})
    }
    private let currentYear = BehaviorRelay<Int>.init(value: 1970)
    
    private let currentMonth = BehaviorRelay<Int>.init(value: 1)
    
    private func daysInMonth(year: Int, month: Int) -> Int {
        var components = DateComponents()
        components.year = year
        components.month = month
        components.day = 1 // 设置为该月的第一天

        guard let date = Calendar.current.date(from: components) else { return 0 }
        let range = Calendar.current.range(of: .day, in: .month, for: date)
        return range!.count
    }
    
    private let currentDay = BehaviorRelay<Int>.init(value: 1)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.configView()
    }
    
    private func configView() {
        self.pickerView.delegate = self
        self.pickerView.dataSource = self
        self.currentYear
            .subscribe(onNext: { [weak self] value in
                self?.pickerView.reloadAllComponents()
            })
            .disposed(by: self.bag)
        self.currentMonth.subscribe(onNext: { [weak self] value in
            self?.pickerView.reloadComponent(0)
            self?.pickerView.reloadComponent(1)
        })
        .disposed(by: self.bag)
        self.currentDay.subscribe(onNext: { [weak self] value in
            self?.pickerView.reloadComponent(0)
        })
        .disposed(by: self.bag)
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        let subviews = self.pickerView.subviews
        let arr = subviews.first
        if let subviewCache = arr?.value(forKey: "subviewCache") as? [UIView] {
            let first = subviewCache.first
            let middleView = first?.value(forKey: "middleContainerView") as? UIView
            middleView?.backgroundColor = UIColor.hex(with: "#126BFB")
            middleView?.layer.cornerRadius = 8
            middleView?.layer.masksToBounds = true
        }
        
    }

    @IBAction func closeAction(_ sender: UIButton) {
        self.dismiss(animated: false)
    }
    
    @IBAction func confirmAction(_ sender: UIButton) {
        let title = String(format: "%.2d", self.currentDay.value) + "-" + String(format: "%.2d", self.currentMonth.value) + "-" + String(format: "%.2d", self.currentYear.value)
        self.confirm.onNext(title)
        self.dismiss(animated: false)
    }

}

extension DatePickerViewController: UIPickerViewDelegate, UIPickerViewDataSource {
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if component == 0 {
            let year = self.currentYear.value
            let month = self.currentMonth.value
            return self.daysInMonth(year: year, month: month)
        } else if component == 1 {
            return 12
        } else {
            return self.years.count
        }
    }
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 3
    }
    
    func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
        let selectedRow = pickerView.selectedRow(inComponent: component)
        var title = ""
        if component == 0 {
            let year = self.currentYear.value
            let month = self.currentMonth.value
            let days = self.daysInMonth(year: year, month: month)
            if days > row {
                title = String(format: "%.2d", row + 1)//"\(row + 1)"
            }
        } else if component == 1 {
            title = String(format: "%.2d", row + 1)
        } else {
            if self.years.count > row {
                title = "\(self.years[row])"
            }
        }
        let s = NSMutableAttributedString(string: title, attributes: [.foregroundColor: selectedRow == row ? UIColor.white : UIColor.hex(with: "#121011"), .font: UIFont.systemFont(ofSize: 14)])
        return s
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if component == 0 {
            self.currentDay.accept(row + 1)
        } else if component == 1 {
            self.currentMonth.accept(row + 1)
        } else {
            let year = self.years[row]
            self.currentYear.accept(year)
        }
    }
    
    
}
